#include<vector>
#include<algorithm>
using namespace std;

class Solution {
    void getMinMax(const vector<int>& nums,int start,int end, int& min_, int& max_) {
        min_ = INT32_MAX;
        max_ = INT32_MIN;
        while (start < end) {
            min_ = min(nums[start], min_);
            max_ = max(nums[start], max_);
            ++start;
        }
    }

public:
    int longestSubarray(vector<int>& nums, int limit) {
        int left = 0, right = 0;
        int max_ = INT32_MIN, min_ = INT32_MAX;
        while (right < nums.size()) {
            bool flag = false;
            while (right < nums.size()) {
                max_ = max(max_, nums[right]);
                min_ = min(min_, nums[right]);
                ++right;
                if (abs(max_ - min_) > limit) {
                    if (max_ == nums[left] || min_ == nums[left]) {
                        getMinMax(nums, left + 1, min(right + 1, int(nums.size())), min_, max_);
                    }
                    ++left;
                }
            }
        }
        return right - left;
    }
};